#include "SpriteAnimation.h"


SpriteAnimation::SpriteAnimation(void)
{
	_animationFrames = NULL;
	_sprite = NULL;
	_spriteBatchNode = NULL;
}


SpriteAnimation::~SpriteAnimation(void)
{
	_sprite->stopAllActions();
	CC_SAFE_RELEASE(_animationFrames);
	CC_SAFE_RELEASE(_sprite);
	CC_SAFE_RELEASE(_spriteBatchNode);
}

bool SpriteAnimation::initWith( string textureFileName, string plistFileName, string prefix, int begin, int end )
{
	if (!CCNode::init())
		return false;

	_timeStep = 0.1f;
	CCSpriteBatchNode* spritebatch   = CCSpriteBatchNode::create(textureFileName.c_str());
	CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(plistFileName.c_str());

	char name[100]= {0};
	sprintf(name, "%s%d", prefix.c_str(), 1);
	sprintf(name, "%s%s", name, ".png");
	CCSprite* sprite = CCSprite::createWithSpriteFrameName(name);
	sprite->setAnchorPoint(CCPointZero);
	setContentSize(sprite->getContentSize());
	
	if (!sprite && !spritebatch)
		return false;
	spritebatch->addChild(sprite);
	addChild(spritebatch);
	setSprite(sprite);
	setSpriteBatchNode(spritebatch);

	// Animation
	CCArray* walkAnimFrames = CCArray::create();
	for (int i = begin; i <= end; i++)
	{
		sprintf(name, "%s%d", prefix.c_str(), i);
		sprintf(name, "%s%s", name, ".png");
		CCSpriteFrame* frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(name);
		walkAnimFrames->addObject(frame);
	}

	setAnimationFrames(walkAnimFrames);

	
	return true;
}

SpriteAnimation* SpriteAnimation::createWith( string textureFileName, string plistFileName, string prefix, int begin, int end )
{
	SpriteAnimation* pRet = new SpriteAnimation();
	
	if (pRet && pRet->initWith(textureFileName, plistFileName, prefix, begin, end))
	{
		pRet->autorelease();
		return pRet;
	} else
	{
		delete pRet;
		pRet = NULL;
		return NULL;
	}
}

void SpriteAnimation::playAnimation( bool isLoop /*= true*/ )
{
	CCAnimation* animation = CCAnimation::createWithSpriteFrames(_animationFrames, _timeStep);
	if (isLoop)
	{
		CCAnimate* animate = CCAnimate::create(animation);
		animate->setTag(1);
		//sprite ->runAction(CCSequence::create(animate, CCCallFuncN::create(this, callfuncN_selector(HelloWorld::onDoneMove)), NULL));
		_sprite->runAction(CCRepeatForever::create(animate));
		
	} else
	{
		CCAnimate* animate = CCAnimate::create(animation);
		animate->setTag(1);
		_sprite->runAction(animate);
	}
}

void SpriteAnimation::stopAnimation()
{
	_sprite->stopAllActions();
}

bool SpriteAnimation::isDone()
{
	CCAnimate* animate = dynamic_cast<CCAnimate*>(_sprite->getActionByTag(1));
	if (!animate)
		return true;
	return animate->isDone();
}

void SpriteAnimation::setOpacity( int a )
{
	_sprite->setOpacity(a);
}
